package demo4;

/**
 * 普通队列
 */
public class MyBlockingQueue {
    //定义一个数组
    private  Integer[] arr;
    //定义数组的头和尾
    private volatile int head;
    private volatile int tail;
    //数组的长度
    private volatile int size;
    //构造方法
    public MyBlockingQueue(int capacity) {
        if(capacity<=0){
            throw new RuntimeException("队列容量必须要大于0");
        }
        this.arr = new Integer[capacity];
    }
    //插入数据
    public void put(Integer value) throws InterruptedException {
        synchronized (this) {
            while (size == arr.length) {
                this.wait();
            }
            arr[tail] = value;
            tail++;
            if (tail == arr.length) tail = 0;
            size++;
            this.notifyAll();
        }
    }
    //取出数据
    public synchronized Integer take() throws InterruptedException {
        while (size==0){
            this.wait();
        }
        int temp=arr[head];
        arr[head]=0;
        head++;
        if(head==arr.length) head=0;
        size--;
        this.notifyAll();
        return temp;
    }
}
